package com.ihome.framework.core.nos;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ihome.framework.core.log.Log;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.GetObjectRequest;
import com.netease.cloud.services.nos.model.NOSObject;

public class NosDownloader implements Runnable {
	private static final Logger LOG = LoggerFactory.getLogger(NosDownloader.class);

	private NosClient nosClient;

	private String bucket;

	private String key;

	private long startBytes;

	private long endBytes;

	private CountDownLatch cdl;

	private String destFileName;

	public NosDownloader(NosClient nosClient, String bucket, String key, long startBytes, long endBytes,
			CountDownLatch ctl, String destFileName) {
		super();
		this.nosClient = nosClient;
		this.bucket = bucket;
		this.key = key;
		this.startBytes = startBytes;
		this.endBytes = endBytes;
		this.cdl = ctl;
		this.destFileName = destFileName;
	}

	@Override
	public void run() {
		InputStream is = null;
		OutputStream os = null;
		try {
			LOG.info(Log.op("NosDownloader.run")
					.msg("start to download file " + destFileName + "[" + startBytes + "-" + endBytes + "]")
					.toString());
			GetObjectRequest req = new GetObjectRequest(bucket, key);
			req.setRange(startBytes, endBytes);
			NOSObject object = nosClient.getObject(req);
			LOG.info(Log.op("NosDownloader.run").msg("object.length " + object.getObjectMetadata().getContentLength())
					.toString());
			is = object.getObjectContent();
			os = new FileOutputStream(new File(destFileName));
			IOUtils.copy(is, os);
			os.flush();
		} catch (Exception ex) {
			LOG.error(Log.op("NosDownloader.run").msg("download file error").toString(), ex);
		} finally {
			IOUtils.closeQuietly(is);
			IOUtils.closeQuietly(os);
			cdl.countDown();
			LOG.info(Log.op("NosDownloader.run").msg("finish to download file " + destFileName).toString());
		}
	}

}
